<?php

namespace IDock\Insurance\ACIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\ACIC\ACICEnums;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumFactorPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\Premium\PremiumTaxPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllACICResponse
{
    protected function errorTrans($error): string
    {

        $error = str_replace(['', "\r\n", "\r", "\n"], ['', '', '', ''], $error);

        switch ($error) {
            case "E52--商业投保查询与平台交互异常车险平台返回信息 使用性质为220时,不允许投保险种：0301604*":
                return "E52--商业投保查询与平台交互异常车险平台返回信息 使用性质为非营业企业时,不允许投保险种：机动车第三者责任保险-附加法定节假日限额翻倍险";
        }

        return '';
    }


    public function printerInit(): Response
    {
        $premiumInquiryPrinter = new PremiumInquiryPrinter();

        $premiumInquiryPrinter->success = true;

        if ($this->repeat($premiumInquiryPrinter)) {

            $this->printer = $premiumInquiryPrinter;
            return $this;
        }

        $premiumInquiryPrinter->isNewEnergy = $this->get('BI', [])['NewFuelVhlFlag'] ?? false;

        $ciData = $this->get('CI');

        //交强险
        if ($ciData) {

            $premiumInquiryPrinter->ciInquiryNo = $ciData['CQueryNo'] ?? '';

            $ciPremiumPrinter = new PremiumCIPrinter();
            $ciPremiumPrinter->ciPremium = $ciData['Prem'] ?? '';
            $ciPremiumPrinter->ciBasePremium = $ciData['DPrem'] ?? '';
            $ciPremiumPrinter->ciDiscount = $ciData['Discount'] ?? '';

            $premiumInquiryPrinter->ciPremiumPrinter = $ciPremiumPrinter;

            //车船税
            $premiumTaxPrinter = new PremiumTaxPrinter();
            $premiumTaxPrinter->carShipTax = $ciData['TaxDetail']['AnnualTaxDue'] ?? '';
            $premiumTaxPrinter->overdue = $ciData['TaxDetail']['SumOverdue'] ?? '';
            $premiumTaxPrinter->payBackTax = $ciData['TaxDetail']['SumTaxDefault'] ?? '';
            $premiumTaxPrinter->thisYearTax = $premiumTaxPrinter->carShipTax;

            $premiumInquiryPrinter->carTaxPrinter = $premiumTaxPrinter;
        }

        $biData = $this->get('BI') ?? [];

        //商业险
        if ($biData) {

            $premiumInquiryPrinter->biInquiryNo = $biData['BQueryNo'] ?? '';
            $premiumBIPrinter = new PremiumBIPrinter();

            $premiumBIPrinter->biPremium = $biData['BPremium'] ?? '';
            $premiumBIPrinter->biDiscount = $biData['Discount'] ?? '';
            $premiumBIPrinter->biBasePremium = $biData['BDPremium'] ?? '';

            $premiumInquiryPrinter->biPremiumPrinter = $premiumBIPrinter;
        }
        $premiumInquiryPrinter->ncdFactor = $this->get('BI')['NCD'] ??'';
        //商业险险种
        $coverageList = $biData['CoverageItem'] ?? [];

        if ($coverageList and !isset($coverageList[0])) {
            $tmp = $coverageList;
            $coverageList = [];
            $coverageList[] = $tmp;
        }

        foreach ($coverageList as $value) {

            $premiumCoveragePrinter = new PremiumCoveragePrinter();

            $premiumCoveragePrinter->premium = $value['Premium'] ?? '';
            $premiumCoveragePrinter->amount = $value['Sumlimit'] ?? '';


            $coverageCode = $value['CoverageCode'];

            $premiumCoveragePrinter->coverageCode = array_search($coverageCode, ACICEnums::$coverageCode);

            //新能源险种代码变更
            if ($premiumInquiryPrinter->isNewEnergy) {
                $premiumCoveragePrinter->coverageCode = 'C1' . substr($premiumCoveragePrinter->coverageCode, '2', 4);
            }

            $premiumCoveragePrinter->coverageName = IDockEnums::$coverageCode[$premiumCoveragePrinter->coverageCode];
            $premiumCoveragePrinter->discount = $biData['Discount'] ?? '';

            $premiumInquiryPrinter->coverageListAppend($premiumCoveragePrinter);

        }
        //特约
        $agreementCi = $ciData['SpecialContact'] ?? [];

        if ($agreementCi) {
            $agreementCi = explode('@', $agreementCi);
        }

        foreach ($agreementCi as $ciAgr) {
            $special = new SpecialClausesPrinter();
            $special->autoFlag = '1';
            $special->riskType = 'TCI';
            $special->clauseType = '0';
            $special->clauseCode = md5($ciAgr.'TCI');
            $special->clauseName = '';
            $special->clauseContent = $ciAgr;
            $premiumInquiryPrinter->specialClausesAppend($special);
        }

        $agreementBi = $biData['SpecialContact'] ?? [];

        if ($agreementBi) {
            $agreementBi = explode('@', $agreementBi);
        }

        foreach ($agreementBi as $biAgr) {
            $special = new SpecialClausesPrinter();
            $special->autoFlag = '1';
            $special->riskType = 'VCI';
            $special->clauseType = '0';
            $special->clauseCode = md5($biAgr.'VCI');
            $special->clauseName = '';
            $special->clauseContent = $biAgr;
            $premiumInquiryPrinter->specialClausesAppend($special);
        }

        $this->printer = $premiumInquiryPrinter;

        //系数配置
        $factorPrinter = new PremiumFactorPrinter();

        if ($ciData) {
            $factorPrinter->TCIFactorAppend('交强单交强预期赔付率','TCICIExpectedLossRatio',$ciData['CIExpectedLossRatio'] ?? '');
            $factorPrinter->TCIFactorAppend('交强单商业预期赔付率','TCIBIExpectedLossRatio',$ciData['BIExpectedLossRatio'] ?? '');
            $factorPrinter->TCIFactorAppend('交强单整单预期赔付率','TCITExpectedLossRatio',$ciData['TExpectedLossRatio'] ?? '');
        }

        if ($biData) {
            $factorPrinter->VCIFactorAppend('光博自主定价系数','AutoPriceDiscount',$biData['AutoPriceDiscount'] ?? '');
            $factorPrinter->VCIFactorAppend('商业单交强预期赔付率','VCICIExpectedLossRatio',$biData['CIExpectedLossRatio'] ?? '');
            $factorPrinter->VCIFactorAppend('商业单商业预期赔付率','VCIBIExpectedLossRatio',$biData['BIExpectedLossRatio'] ?? '');
            $factorPrinter->VCIFactorAppend('商业单整单预期赔付率','VCITExpectedLossRatio',$biData['TExpectedLossRatio'] ?? '');
            $factorPrinter->VCIFactorAppend('建议折扣','AdviceDiscount',$biData['AdviceDiscount'] ?? '');
        }
        //车惠达评分
        $CHDRiskInfo = $this->get('CHDRiskInfo');
        if ($CHDRiskInfo = json_decode($CHDRiskInfo,true)) {

            $factorPrinter->ComFactorAppend('车慧达分数','priScore',$CHDRiskInfo['priScore'] ?? '');
            $factorPrinter->ComFactorAppend('车慧达分档','priScore',$CHDRiskInfo['priTranche'] ?? '');
        }

        $premiumInquiryPrinter->premiumFactorPrinter = $factorPrinter;

        return $this;
    }

    public function buildCoverage($isEnergy,array $orgList)
    {
        $orgList = array_combine(array_column($orgList, 'coverageCode'), $orgList);

        foreach ($this->printer->coverageList as &$coverage) {
            /*** @var $coverage PremiumCoveragePrinter */

            if ($isEnergy) {
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, 2, 4);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            }

            if (!$coverage->amount) {
                $coverage->amount = $orgList[$coverage->coverageCode]->amount ?? '';
            }

            $coverage->quantity = $orgList[$coverage->coverageCode]->quantity ?? '';
            $coverage->unitAmount = $orgList[$coverage->coverageCode]->unitAmount ?? '';
            //服务次数回写
            $coverage->serviceTimes = $orgList[$coverage->coverageCode]->serviceTimes ?? '';
        }
    }

    /**
     * 重复投保提示
     * @param PremiumInquiryPrinter $premiumInquiryPrinter
     * @return bool
     */
    private function repeat(PremiumInquiryPrinter $premiumInquiryPrinter): bool
    {
        $ciRepeat = $this->get('CI')['DupFlag'] ?? '0';

        $biRepeat = $this->get('BI')['DupFlag'] ?? '0';

        $ciMeg = $this->get('CI')['RepeatInfo']['RepeatDesc'] ?? '';
        $biMeg = $this->get('BI')['RepeatInfo']['RepeatDesc'] ?? '';

        if ($ciRepeat == 1 or $biRepeat == 1) {
            $repeatMessage = implode("\r\n", array_filter([$ciMeg, $biMeg]));

            $this->getRepeatData($premiumInquiryPrinter, $ciMeg, $biMeg);

            $premiumInquiryPrinter->success = false;
            $premiumInquiryPrinter->repeatMessage = $repeatMessage;
            return true;
        }

        return false;
    }

    /**
     * 重复投保
     * @param PremiumInquiryPrinter $premiumInquiryPrinter
     * @param $ciMeg
     * @param $biMeg
     * @return void
     */
    public function getRepeatData(PremiumInquiryPrinter $premiumInquiryPrinter, $ciMeg, $biMeg)
    {
        if (preg_match('/终保日期 ([\d\s:-]+)/', $ciMeg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $premiumInquiryPrinter->repeatInsurePrinter['ciStartData'] = $ciStartData;
            }
        }

        if (preg_match('/终保日期：([\d]+)/', $biMeg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));

                $premiumInquiryPrinter->repeatInsurePrinter['biStartData'] = $biStartData;
            }
        }

        if ($premiumInquiryPrinter->repeatInsurePrinter['ciStartData'] or $premiumInquiryPrinter->repeatInsurePrinter['biStartData']) {
            $premiumInquiryPrinter->repeatInsuredFlg = true;
        }
    }
}
